<template>
  <section>
    <van-sticky>
      <PageHeader title="线下活动"/>
    </van-sticky>

    <van-field
      v-model="activity.name"
      label="名称"
      required
      placeholder="请输入活动名称"
      :rules="[{ required: true, message: '请输入活动名称' }]">
    </van-field>

    <van-field
      v-model="activity.region"
      disabled
      required
      label="举办地"
      placeholder="请选择举办城市"
      :rules="[{ required: true, message: '请选择举办城市' }]">
      <template #button>
        <van-button size="small" type="primary" @click="onShowRegionPopup">选择</van-button>
      </template>
    </van-field>

    <van-field
      v-model="activity.address"
      label="地址"
      required
      placeholder="请输入活动地址"
      :rules="[{ required: true, message: '请输入活动地址' }]">
    </van-field>

    <van-cell-group title="活动时间">
      <van-field
        v-model="activity.begin_time_str"
        disabled
        required
        label="开始时间"
        placeholder="请选择开始时间"
        :rules="[{ required: true, message: '请选择开始时间' }]">
        <template #button>
          <van-button size="small" type="primary" @click="showActivityTimePopup('begin')">选择</van-button>
        </template>
      </van-field>

      <van-field
        v-model="activity.end_time_str"
        disabled
        required
        label="结束时间"
        placeholder="请选择结束时间"
        :rules="[{ required: true, message: '请选择结束时间' }]">
        <template #button>
          <van-button size="small" type="primary" @click="showActivityTimePopup('end')">选择</van-button>
        </template>
      </van-field>
    </van-cell-group>

    <van-field
      v-model="activity.apply_deadline_time_str"
      disabled
      required
      label="报名截止时间"
      placeholder="请选择报名截止时间"
      :rules="[{ required: true, message: '请选择报名截止时间' }]">
      <template #button>
        <van-button size="small" type="primary" @click="showActivityTimePopup('deadline')">选择</van-button>
      </template>
    </van-field>

    <van-cell-group title="费用">
      <van-field
        v-model="activity.charge_male"
        type="number"
        label="男"
        required
        placeholder="请输入男会员费用">
        <template #button>
          <label>元</label>
        </template>
      </van-field>

      <van-field
        v-model="activity.charge_female"
        type="number"
        label="女"
        required
        placeholder="请输入女会员费用">
        <template #button>
          <label>元</label>
        </template>
      </van-field>
    </van-cell-group>

    <van-cell-group title="人数">
      <van-field
        v-model="activity.amount_male"
        type="digit"
        label="男"
        required
        placeholder="请输入男会员人数">
        <template #button>
          <label>人</label>
        </template>
      </van-field>

      <van-field
        v-model="activity.amount_female"
        type="digit"
        label="女"
        required
        placeholder="请输入女会员人数">
        <template #button>
          <label>人</label>
        </template>
      </van-field>
    </van-cell-group>

    <van-cell-group title="活动图">
      <van-uploader v-model="imgList" multiple :max-count="1" :before-read="beforeUploadRead"
                    :after-read="afterUploadRead" @delete="onImgDelete"/>
    </van-cell-group>

    <van-field
      v-model="activity.apply_requirement"
      label="报名要求"
      placeholder="请输入报名要求"
      type="textarea"
      autosize
      rows="5">
    </van-field>

    <van-cell-group title="详情">
      <Ueditor :defaultMsg="activity.detail" :config="ueConfig" id="ue" ref="ue"/>
    </van-cell-group>

    <div class="pd10">
      <van-button round block type="info" @click="save">保 存</van-button>
    </div>

    <van-popup v-model="showRegionPopup" round position="bottom">
      <van-cascader
        v-model="selectedRegions"
        title="请选择所在地区"
        :options="provinceList"
        @close="showRegionPopup = false"
        @change="onRegionCascaderChange"
        @finish="onRegionCascaderFinish"
      />
    </van-popup>

    <van-popup v-model="datetimePickerPopupVisible" round position="bottom">
      <van-datetime-picker
        v-model="activityTime"
        type="datetime"
        title="活动时间"
        @confirm="onActivityTimeConfirm"/>
    </van-popup>
  </section>
</template>

<script>
  import Vue from 'vue';
  import {Toast, Dialog, Sticky, Field, Form, Cell, CellGroup, Popup, Cascader, DatetimePicker, Uploader} from 'vant';
  import {
    BASE_PATH,
    BASE_STATIC_URL,
    fileUploadByBase64Uri,
    regionChildrenUri,
    ueFileUploadUri,
    activityAddUri,
    activityEditUri,
    activityInfoUri
  } from "../../common/api";
  import PageHeader from "../componets/PageHeader";
  import Ueditor from "../../components/Ueditor";

  Vue.use(Toast).use(Dialog).use(Sticky).use(Field).use(Form).use(Cell).use(CellGroup).use(Popup).use(Cascader).use(DatetimePicker).use(Uploader);

  export default {
    components: {
      PageHeader,
      Ueditor
    },
    data() {
      const ueServerUrl = ueFileUploadUri + '?upload_token=' + this.GLOBAL.userInfo.upload_token;
      return {
        ueConfig: {
          UEDITOR_HOME_URL: BASE_PATH + '/static/js/ueditor/',
          serverUrl: ueServerUrl,
          initialFrameWidth: null,
          initialFrameHeight: 400
        },
        activity: {
          id: 0,
          name: '',
          region_id: 0,
          region: '',
          address: '',
          img_id: 0,
          img_url: '',
          begin_time: 0,
          end_time: 0,
          begin_time_str: '',
          end_time_str: '',
          apply_deadline_time: 0,
          apply_deadline_time_str: '',
          charge_male: 0.00,
          charge_female: 0.00,
          amount_male: 0,
          amount_female: 0,
          apply_requirement: '',
          detail: ''
        },
        imgList: [],
        showRegionPopup: false,
        selectedRegions: '',
        provinceList: [],
        cityList: [],

        datetimePickerPopupVisible: false,
        activityTime: new Date(),
        activityTimeType: ''
      }
    },
    methods: {
      beforeUploadRead(file) {
        if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
          Toast('请上传 jpg/png 格式图片');
          return false;
        }
        return true;
      },
      afterUploadRead(file) {
        file.status = 'uploading';
        file.message = '上传中...';

        const that = this;
        that.$http.post(fileUploadByBase64Uri, {
          fileData: file.content,
          upload_token: that.GLOBAL.userInfo.upload_token
        }, {emulateJSON: true}).then(response => {
          let {msg, code, file_id, url} = response.body;
          if (code != 0) {
            Toast.fail(msg)
          } else {
            that.activity.img_id = file_id;
            that.activity.img_url = url;
            file.status = 'done';
            file.message = '';
          }
        }, response => {
          Toast.fail('发生错误')
        })
      },
      onImgDelete(file, detail) {
        const that = this;
        that.activity.img_id = 0;
        that.activity.img_url = '';
      },
      getRegions(parentId, callback) {
        const that = this;
        const url = regionChildrenUri + '?parent_id=' + parentId;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            Toast.fail(msg);
          } else {
            callback(data.regions);
          }
        }, response => {
          // error callback
        })
      },
      onRegionCascaderChange(option) {
        const tabIndex = option.tabIndex;
        const value = option.value;
        if (tabIndex == 0) {
          if (value > 0) {
            const provinceList = this.provinceList;
            let provinceIndex = 0;
            for (let i = 0; i < provinceList.length; i++) {
              if (value == provinceList[i].value) {
                provinceIndex = i;
                break;
              }
            }
            this.getRegions(value, (regions) => {
              let children = [];
              children.push({
                text: '不限',
                value: 0
              });
              for (let i = 0; i < regions.length; i++) {
                children.push({
                  text: regions[i].region_name,
                  value: regions[i].region_id
                })
              }
              let province = provinceList[provinceIndex];
              province.children = children;
              this.$set(provinceList, provinceIndex, province);
            })
          } else {
            let children = [];
            children.push({
              text: '不限',
              value: 0
            });
            const provinceList = this.provinceList;
            let provinceIndex = 0;
            let province = provinceList[provinceIndex];
            province.children = children;
            this.$set(provinceList, provinceIndex, province);
          }
        }
      },
      onRegionCascaderFinish({selectedOptions}) {
        this.activity.region_id = selectedOptions[1].value;
        this.activity.region = selectedOptions[0].text + '-' + selectedOptions[1].text;
        this.showRegionPopup = false;
      },
      onShowRegionPopup() {
        this.showRegionPopup = true;
      },
      showActivityTimePopup(type) {
        this.activityTimeType = type;
        this.datetimePickerPopupVisible = true;
      },
      onActivityTimeConfirm(value) {
        if (this.activityTimeType == 'begin') {
          this.activity.begin_time = value.getTime() / 1000;
          this.activity.begin_time_str = value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate() + ' ' + value.getHours() + ':' + value.getMinutes();
        } else if (this.activityTimeType == 'end') {
          this.activity.end_time = value.getTime() / 1000;
          this.activity.end_time_str = value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate() + ' ' + value.getHours() + ':' + value.getMinutes();
        } else if (this.activityTimeType == 'deadline') {
          this.activity.apply_deadline_time = value.getTime() / 1000;
          this.activity.apply_deadline_time_str = value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate() + ' ' + value.getHours() + ':' + value.getMinutes();
        }
        this.datetimePickerPopupVisible = false;
      },
      save() {
        if (this.activity.name.length == 0 || this.activity.region_id == 0 || this.activity.address.length == 0
          || this.activity.begin_time == 0 || this.activity.end_time == 0 || this.activity.apply_deadline_time == 0) {
          return;
        }
        if (this.activity.img_id == 0) {
          Toast.fail('请上传图片');
          return;
        }
        if (this.activity.end_time <= this.activity.begin_time) {
          Toast.fail('结束时间不能大于开始时间');
          return;
        }
        if (this.activity.apply_deadline_time >= this.activity.begin_time) {
          Toast.fail('截止时间不能大于开始时间');
          return;
        }
        this.activity.detail = this.$refs.ue.getUEContent();
        let url;
        if (this.activity.id == 0) {
          url = activityAddUri;
        } else {
          url = activityEditUri;
        }

        const that = this;
        that.$http.post(url, that.activity, {emulateJSON: true}).then(response => {
          let {msg, code, data} = response.body
          if (code != 0) {
            Toast.fail(msg)
          } else {
            Toast.success('保存成功');
            that.$router.back();
          }
        }, response => {
          Toast.fail('发生错误')
        })
      },
      getInfo() {
        const that = this;
        this.$http.get(activityInfoUri + '?id=' + this.$route.params.id).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast.fail(msg);
          } else {
            that.activity = data.activity;
            that.imgList.push({url: data.activity.img_url});
            that.$refs.ue.setUEContent(data.activity.detail);
          }
        }, response => {
          // error callback
        })
      }
    },
    mounted: function () {
      if (this.$route.name == 'ActivityEdit') {
        this.activity.id = this.$route.params.id;
        this.getInfo();
      }

      this.getRegions(1, (regions) => {
        let provinceList = [];
        provinceList.push({
          text: '不限',
          value: 0,
          children: []
        });
        for (let i = 0; i < regions.length; i++) {
          provinceList.push({
            text: regions[i].region_name,
            value: regions[i].region_id,
            children: []
          })
        }
        this.provinceList = provinceList;
      });
    }
  }
</script>

<style scoped>

</style>
